/**
 * Author: Todd Kerpelman
 * Date: 5/15/12
 * Time: 12:46 PM
 *
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

var flashIsReady = function() {
  registerEvents();
  getFolksInHangout();
};

var getFolksInHangout = function() {
    console.log("Flash object is requesting folks in hangout");
    console.log("I have ",gapi.hangout.getParticipants()," to report")
    document.getElementById('HangoutInSpace')
        .tellFlashUsersInHangout(gapi.hangout.getParticipants());
};


var userAddedCallback = function(userAddedData)
{
  console.log("User added! Hooray", userAddedData);

  for (var i =0; i<userAddedData.addedParticipants.length; i++) {
    var newUser = userAddedData.addedParticipants[i];
    document.getElementById('HangoutInSpace')
             .tellFlashUserAdded(newUser);
  }
};

var userRemovedCallback = function(userLeftData)
{
  console.log("User removed! Awww", userLeftData);
  for (var i=0; i<userLeftData.removedParticipants.length; i++) {
    var departingUser = userLeftData.removedParticipants[i];
    document.getElementById('HangoutInSpace')
        .tellFlashUserRemoved(departingUser);
  }
};
var volumesChangedCallback = function(volumes) {
  document.getElementById('HangoutInSpace')
        .tellFlashNewVolumes(volumes);
};

var registerEvents = function() {
  gapi.hangout.onParticipantsAdded.add(userAddedCallback);
  gapi.hangout.onParticipantsRemoved.add(userRemovedCallback);
  gapi.hangout.av.onVolumesChanged.add(volumesChangedCallback);
};

var hangoutInit = function() {
  // When API is ready...

  gapi.hangout.onApiReady.add(
	function(eventObj) {
    try {
      console.log("Hooray! Hangout app started!");
      swfobject.embedSWF(
            "HangoutInSpace.swf", "flashContent",
            "640", "480",
            swfVersionStr, xiSwfUrlStr,
            flashvars, params, attributes);

    } catch (e) {
      console.log("Error in startup");
      console.log(e.stack);
    }
  }
  );
};

gapi.load('auth', hangoutInit);
